import axios from 'axios';

Date.prototype.Format = function(fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
class TApi {
    constructor() {
        this.apiUrl = "/yysvrapi";
        this.resPath = "res"
        this.dbCode = "adminV2_db";
    }
    fixedFloat(value, decSize) {
        var res = value;
        try {
            var pos = (value + "").indexOf(".")
            if (pos > 0) {
                res = parseFloat((value + "000000").substring(0, 1 + pos + decSize));
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    getSessionObj(key, defaultObj) {
        var res = defaultObj
        try {
            var data = window.sessionStorage.getItem(key)
            if (data && data != null && data != "") {
                res = JSON.parse(data)
            }
        } catch (error) {
            console.log(error)
        }
        return res

    };
    setSessionObj(key, obj) {
        try {
            window.sessionStorage.setItem(key, JSON.stringify(obj))
        } catch (error) {
            console.log(error)
        }
    };
    callApi(compCode, action, params, method = "post") {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var url = [me.apiUrl, compCode, action].join("/")
                if (method.toLowerCase() == "post") {
                    var ps = (params && params != null) ? params : {};
                    console.log('callApi', url, ps)
                    axios.post(url, ps, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(_res => {
                        su(_res.data)
                    })
                } else if (method.toLowerCase() == "get") {
                    var ps = (params && params != null) ? params : {};
                    if ((Object.keys(ps)).length > 0) {
                        if (url.indexOf("?") > 0) {
                            url = url + "&"
                        } else {
                            url = url + "?"
                        }
                        var kvs = Object.keys(ps).map(k => {
                            return k + "=" + ps[k];
                        })
                        url = url + kvs.join("&")
                    }
                    axios.get(url).then(_res => {
                        su(_res.data)
                    })
                } else {
                    su()
                }
            } catch (error) {
                su(res)
            }
        });
    };
    getRes(resPath) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var url = [me.apiUrl, me.resPath, resPath].join("/")
                if (url.indexOf("?") < 0) {
                    url = url + "?t=" + (new Date()).getTime();
                } else {
                    url = url + "&t=" + (new Date()).getTime();
                }
                console.log('get res :', url)
                try {
                    axios.get(url).then(_res => {
                        console.log(_res)
                        su(_res.data)
                    }).catch(_err => {
                        su()
                    })

                } catch (err) {
                    console.log(err)
                    su({})
                }
            } catch (error) {
                su(res)
            }
        });
    };
    getResList(resPathList) {
        var me = this;
        var res = [];
        return new Promise((su, fa) => {
            try {
                if (resPathList.length > 0) {
                    var index = 0;
                    var getItem = () => {
                        if (index < resPathList.length) {
                            try {
                                var resPath = resPathList[index];
                                var url = [me.apiUrl, me.resPath, resPath].join("/")
                                if (url.indexOf("?") < 0) {
                                    url = url + "?t=" + (new Date()).getTime();
                                } else {
                                    url = url + "&t=" + (new Date()).getTime();
                                }
                                console.log('get res :', url)
                                axios.get(url).then(_res => {
                                    res.push(_res.data);
                                    index = index + 1;
                                    getItem();
                                })
                            } catch (erItem) {
                                console.log(erItem)
                                res.push("");
                                index = index + 1;
                                getItem();
                            }
                        } else {
                            su(res)
                        }
                    }
                    getItem();
                } else {
                    su(res);
                }

            } catch (error) {
                su(res)
            }
        });
    };
    uploadObj(obj, dataPath) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                console.log('ipload')
                var ps = {
                    obj,
                    dataPath
                }
                me.callApi("admin2025", "uploadObj", ps).then(_queryRes => {
                    su(_queryRes)
                })
            } catch (error) {
                su(res)
            }
        });
    };
    query(dbKey, params) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    key: dbKey,
                    params
                }
                me.callApi(me.dbCode, "query", ps).then(_queryRes => {
                    var flag = _queryRes && _queryRes.result && _queryRes.status == 1;
                    su(flag ? _queryRes.result : { status: 0 });
                })
            } catch (error) {
                su(res)
            }
        });
    };
    execProc(procName, keyValues = {}) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    procName: procName,
                    keyValues
                }
                me.callApi(me.dbCode, "execProc", ps).then(_queryRes => {
                    var flag = _queryRes && _queryRes.result && _queryRes.status == 1;
                    su(flag ? _queryRes.result : { status: 0 });
                })
            } catch (error) {
                su(res)
            }
        });
    };
    createRow(table, fieldValues) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    table,
                    fieldValues
                }
                me.callApi(me.dbCode, "createRow", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    updateRow(table, fieldValues, keyValues) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    table,
                    fieldValues,
                    keyValues
                }
                me.callApi(me.dbCode, "updateRow", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    deleteRow(table, keyValues) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    table,
                    keyValues
                }
                me.callApi(me.dbCode, "deleteRow", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    viewRows(view, keyValues) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    view,
                    keyValues
                }
                me.callApi(me.dbCode, "viewRows", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    executeLock(actionCode = 'viewRows', table = "", fieldValues = {}, keyValues = {}) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    actionCode,
                    table,
                    fieldValues,
                    keyValues
                }
                me.callApi(me.dbCode, "executeLock", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    executeAsync(actionCode = 'viewRows', table = "", fieldValues = {}, keyValues = {}) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    actionCode,
                    table,
                    fieldValues,
                    keyValues
                }
                me.callApi(me.dbCode, "executeAsync", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
    getBufferData(bufferCode, action, key, keyValues, forceUpdate = False) {
        var me = this;
        var res = {};
        return new Promise((su, fa) => {
            try {
                var ps = {
                    bufferCode,
                    action,
                    key,
                    keyValues,
                    forceUpdate
                }
                me.callApi(me.dbCode, "viewRows", ps).then(_queryRes => {
                    su(_queryRes.result);
                })
            } catch (error) {
                su(res)
            }
        });
    };
}
class TWsClient {
    constructor() {
        this.settings = {
            wsUrl: "",
            peerType: "console",
            subAcs: ["common"],
            tag: {}
        };
        this.forceCloseFlag = false;
        this._socket = null;
        this._connected = false;
        this._peerId = "";
        this.onlinePeers = {};
        this.info = {};
        this.status = {};
        this.events = {
            "onConnectedChanged": (sender, data) => {},
            "onSessionChanged": (sender, data) => {},
            "onMsg": (sender, data) => {},
        }
    }
    get socket() {
        return this._socket;
    }
    set socket(value) {
        return this._socket = value;
    }
    get connected() {
        return this.socket && this.socket != null && this._connected;
    }
    set connected(value) {
        if (this._connected != value) {
            this._connected = value;
            this.trigger("onConnectedChanged", value);
        }
    }
    get peerId() {
        if (this._peerId == "") {
            this._peerId = "pts_" + parseInt((new Date()).getTime());
        }
        return this._peerId;
    }
    init(wsUrl, peerType, subAcs, onConnectedChanged, onSessionChanged, onMsg, _tag = {}) {
        var me = this;
        try {
            me.settings.wsUrl = wsUrl;
            me.settings.peerType = peerType;
            me.settings.subAcs = subAcs;
            me.settings.tag = _tag;
            if (onConnectedChanged && onConnectedChanged != null) {
                me.events.onConnectedChanged = onConnectedChanged;
            }
            if (onSessionChanged && onSessionChanged != null) {
                me.events.onSessionChanged = onSessionChanged;
            }
            if (onMsg && onMsg != null) {
                me.events.onMsg = onMsg;
            }
        } catch (error) {
            console.log(error)
        }
    };
    trigger(eventCode, eventData) {
        var me = this;
        try {
            var handler = me.events[eventCode];
            if (handler && handler != null) {
                handler(me, eventData)
            }

        } catch (error) {
            console.log(error)
        }
    };
    connect() {
        var me = this;
        try {
            me.forceCloseFlag = false;
            me.disconnect();
            var socket = new WebSocket(me.settings.wsUrl);
            socket.onopen = (event) => {
                console.log('WebSocket连接已建立');
                me.connected = true;
                me.socket = socket;
                var msg = me.getRegistMsg();
                socket.send(JSON.stringify(msg));
            };
            socket.onclose = (event) => {
                console.log('WebSocket连接已关闭');
                me.disconnect();
                if (!me.forceCloseFlag) {
                    console.log(me.forceCloseFlag, '------------------')
                    window.setTimeout(() => {
                        me.connect()
                    }, 3000)
                }
            };
            socket.onerror = (event) => {
                console.log('WebSocket连接失败');
            };
            socket.onmessage = (event) => {
                //console.log('收到消息：', event.data);
                try {
                    var msg = JSON.parse(event.data);
                    me.doOnMsg(msg);
                } catch (er) {
                    console.log(er)
                }
            };
            me.socket = socket;
            /*
            socket.addEventListener('open', (event) => {
                console.log('WebSocket连接已建立');
                me.connected = true;
                me.socket = socket;
                var msg = me.getRegistMsg();
                socket.send(JSON.stringify(msg));
            });
            // 监听消息接收事件
            socket.addEventListener('message', (event) => {
                //console.log('收到消息：', event.data);
                try {
                    var msg = JSON.parse(event.data);
                    me.doOnMsg(msg);
                } catch (er) {
                    console.log(er)
                }
            });
            // 监听连接关闭事件
            socket.addEventListener('close', (event) => {
                console.log('WebSocket连接已关闭');
                me.disconnect();
                if (!me.forceCloseFlag) {
                    window.setTimeout(() => {
                        me.connect()
                    }, 3000)
                }
            });
            // 监听连接关闭事件
            socket.addEventListener('error', (event) => {
                console.log('WebSocket连接失败');
            });
            this.socket = socket;
            socket.connect()
            */

        } catch (error) {
            console.log(error)
        }
    };
    getRegistMsg() {
        var me = this;
        var msg = {
            ac: "regist",
            data: {
                peerId: "",
                peerType: me.settings.peerType,
                subAcs: me.settings.subAcs,
                tag: me.settings.tag
            }
        };
        try {
            msg.data.peerId = me.peerId;
        } catch (er) {
            console.log(er);
        }
        return msg
    };
    disconnect(forceFlag = false) {
        var me = this;
        try {
            me.forceCloseFlag = forceFlag;
            if (me.socket && me.socket != null) {
                me.socket.close();
            }
        } catch (error) {
            console.log(error)
        } finally {
            me.connected = false;
            me.socket = null
        }
    };
    doOnMsg(msg) {
        var me = this;
        try {
            if (msg.ac == 'sessionChanged') {
                me.onlinePeers = msg.data;
                me.trigger('onSessionChanged', me.onlinePeers);
            } else {
                me.trigger('onMsg', msg);
            }

        } catch (error) {
            console.log(error)
        }
    };
    sendMsg(msgType, msgData) {
        var me = this;
        try {
            if (me.connected) {
                var msg = {
                    ac: "pub",
                    data: {
                        msgType: msgType,
                        msgData: msgData
                    }
                };
                msg.data.peerId = me.peerId;
                me.socket.send(JSON.stringify(msg));
            }
        } catch (er) {
            console.log(er);
        }
    };
    sendData(dataObj) {
        var me = this;
        try {
            if (me.connected) {
                var content = JSON.stringify(dataObj);
                me.socket.send(content);
                console.log('sendData', dataObj)

            }
        } catch (er) {
            console.log(er);
        }
    };
}
const api = new TApi();

api.apiUrl = "/infoapi";
api.dbCode = "equ_jumpfull";
export { api, TWsClient }